/**
 * 图片URI生成规则
 */
'use strict';
var C = require('../config');
var _ = require('underscore');

exports.getRandom = function (len) {
  return Math.floor(Math.random() * (Math.pow(10, len) - Math.pow(10, len - 1)) + Math.pow(10, len - 1));
};


/*
 函数：
 str2imgURI
 功能描述：
 将图片字符串转换为URL
 参数：
 S-1234567-654321.jpg
 S-1234567.jpg
 返回：
 { imgType: 'S',
 imgId: '1234567',
 imgRandom: '654321',
 imgExt: 'jpg',
 imgURI: 'http://inmm-test.b0.upaiyun.com/o2o/shop/000/12/34/567-654321.jpg' }
 */
exports.str2imgURI = function (imgStrArray) {  //字符串生成URI规则
  if (!_.isArray(imgStrArray)) {
    imgStrArray = [imgStrArray];
  }
  let retArray = [];
  for (let i in imgStrArray) {
    let imgStr = imgStrArray[i];
    let pattern = C.upyun.urlTypePattern;
    let imgArray = pattern.exec(imgStr);
    if (imgArray) {
      // 匹配成功
      // pattern: /^([SW]{1})-(\d+)-([0-9]{6})\.(jpg|png|webp)$/,  //字符串匹配正则  S-1234567-54321.jpg
      let imgBase = C.upyun.urlTypeArray[imgArray[1]];

      //计算总位数
      let dir = '';
      if (imgBase.pos.length != 0) {
        let totalMum = 0;
        for (let i of imgBase.pos) {
          totalMum += i;
        }

        let id = imgArray[2].toString();

        //pid不足总数位时左边补0
        let imgIdStr = _.str.lpad(id, totalMum, '0');

        //分割目录结构  /111/22/33/444
        let pos = 0;
        for (let i of imgBase.pos) {
          dir += '/' + imgIdStr.substr(pos, i);
          pos += i;
        }
      } else {
        dir = '/' + imgArray[2];
      }


      //添加随机字串
      let file = ''
      if (imgArray[3] != undefined) {
        file = imgArray[3] + '.' + imgArray[4];

      } else {
        file = '.' + imgArray[4];

      }

      let url = C.upyun.urlBase + imgBase.base + dir + file;
      let urlPath = imgBase.base + dir + file;
      retArray.push({
        imgType: imgArray[1],
        imgId: imgArray[2],
        imgRandom: imgArray[3],
        imgExt: imgArray[4],
        imgPath: urlPath,
        imgURI: url
      });
    } else {
      // 错误时返回
      retArray.push({
        imgType: '',
        imgId: 0,
        imgRandom: 0,
        imgExt: 'jpg',
        imgPath: '',
        imgURI: imgStr
      });
    }
  }

  return retArray;
};

/*
 函数：
 str2imgURI
 功能描述：
 将图片id等信息，转换为 图片字符串
 参数：
 'S',1234567,'jpg'
 图片类型，id号，后缀(目前只支持jpg,可选)
 返回：
 S-1234567-654321.jpg
 */
exports.id2imgStr = function (imgType, imgId, imgExt, random) {
  if (imgExt == undefined) {
    imgExt = 'jpg'
  }
  imgType = imgType.toUpperCase();//转换为大写
  if (C.upyun.urlTypeArray[imgType] && imgId > 0 && _.contains(C.upyun.urlTypeArray[imgType].imgExt, imgExt)) {
    if (random) return imgType + '-' + imgId + '-' + random + '.' + imgExt;
    else return imgType + '-' + imgId + '-' + this.getRandom(C.upyun.urlTypeArray[imgType].ran) + '.' + imgExt;
  } else {// 错误时返回 null
    return null;
  }
};